class DrawTool {
    constructor(map) {
        this.map = map
        this._init()
    }

    _init() {
        this.canvas = document.createElement('canvas')
        this.canvas.classList.add('canvas-layer')
        this.canvas.width = map.getCanvas().width
        this.canvas.height = map.getCanvas().height
        this.map.getCanvasContainer().appendChild(this.canvas)
        this.ctx = this.canvas.getContext('2d')
    }

    drawPoint(x, y, options = {
        radius: 5,
        fillColor: 'rgba(255, 0, 0, 0.5)',
        strokeColor: 'red',
        strokeWidth: 2
    }) {
        this.ctx.beginPath()
        this.ctx.save()
        this.ctx.fillStyle = options.fillColor
        this.ctx.strokeStyle = options.strokeColor
        this.ctx.lineWidth = options.strokeWidth
        this.ctx.arc(x, y, options.radius, 0, Math.PI * 2)
        this.ctx.fill()
        this.ctx.stroke()
        this.ctx.restore()
    }

    drawLine(xys = [], options = {
        strokeColor: 'red',
        strokeWidth: 2
    }) {
        this.ctx.beginPath()
        this.ctx.save()
        this.ctx.strokeStyle = options.strokeColor
        this.ctx.lineWidth = options.strokeWidth
        xys.forEach((xy, idx) => {
            idx === 0 ? this.ctx.moveTo(xy[0], xy[1]) : this.ctx.lineTo(xy[0], xy[1])
        })
        this.ctx.fill()
        this.ctx.stroke()
        this.ctx.restore()
    }

    drawPolygon(xys = [], options = {
        fillColor: 'rgba(255, 0, 0, 0.5)',
        strokeColor: 'red',
        strokeWidth: 2
    }) {
        if(xys.length < 4) throw new Error('长度不够，不是一个多边形')
        if(xys[0].join(',') !== xys[xys.length - 1].join(',')) throw new Error('收尾不闭合，不是一个多边形')
        this.ctx.beginPath()
        this.ctx.save()
        this.ctx.fillStyle = options.fillColor
        this.ctx.strokeStyle = options.strokeColor
        this.ctx.lineWidth = options.strokeWidth
        xys.forEach((xy, idx) => {
            idx === 0 ? this.ctx.moveTo(xy[0], xy[1]) : this.ctx.lineTo(xy[0], xy[1])
        })
        this.ctx.closePath()
        this.ctx.fill()
        this.ctx.stroke()
        this.ctx.restore()
    }

    clear() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
    }
}